package com.longrise.android.byjk.plugins.tabthird;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.byjk.R;
import com.longrise.android.byjk.event.CourseDetailEvent;
import com.longrise.android.byjk.event.MineRefreshEvent;
import com.longrise.android.byjk.model.MineMultipleitem;
import com.longrise.android.byjk.model.UserInfor;
import com.longrise.android.byjk.plugins.aboutme.SettingActivity;
import com.longrise.android.byjk.plugins.aboutme.personalInfo.PersonalInfoActivity;
import com.longrise.android.byjk.plugins.course.coursedetail.CourseDetailActivity2;
import com.longrise.android.byjk.plugins.course.mycourse.MyCourseActivity;
import com.longrise.android.byjk.plugins.hra.HraMainActivity;
import com.longrise.android.byjk.plugins.tabthird.invoice.InvoiceManagerActivity;
import com.longrise.android.byjk.widget.view.RoundImageView;
import com.longrise.common.base.BaseFragment;
import com.longrise.common.utils.AppUtil;
import com.longrise.common.utils.DZZWTools;
import com.sobot.chat.SobotApi;
import com.sobot.chat.api.enumtype.SobotChatTitleDisplayMode;
import com.sobot.chat.api.model.Information;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;


/**
 * Created by callxkj on 2017/3/9.
 * 我的页面
 */

public class MineFragment extends BaseFragment<MinePresenter> implements
        MineContract.View, View.OnClickListener, SwipeRefreshLayout.OnRefreshListener, MineCourseAdapter.OnItemClickListener {

    private static final String TAG = "MineFragment";

    private RecyclerView mRcv;
    private View mHeadView;
    private int mOverallYScrol = 0;
    private int mImage_bg_height = 0;
    private ImageView mIvhead_bg;
    private RelativeLayout mRltitle_bg;
    private ImageView mIvtitle_setting;
    private View mTitle_devide;
    private RoundImageView mRiv_head;
    private TextView mTvname;
    private MineCourseAdapter mRcvAdapter;
    private ImageView mIvvip;
    private RelativeLayout mRltitleSetting;
    //private BBswipeRefreshLayout mSrfl;
    private boolean currentFlag = false;
    private View mHeadView2;
    private RelativeLayout mHead2ll1;
    private RelativeLayout mHead2ll2;
    private RelativeLayout mHead2ll3;
    private Information info;
    //智齿客服的appkey
    private String key = "8f75438550d24ab7b7f1eab6a0f36a11";
    private boolean sobot_isOpenNotification = true;//是否打开推送
    private RelativeLayout mHead2ll4;
    private RelativeLayout mHead2ll5;


    @Override
    protected int getLayoutResourse(@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_mine;
    }

    @Override
    public void initView() {
        mRcv = (RecyclerView) mRootView.findViewById(R.id.mine_fragment_irv);
        mRltitle_bg = (RelativeLayout) mRootView.findViewById(R.id.mine_fragment_title_background);
        mIvtitle_setting = (ImageView) mRootView.findViewById(R.id.mine_fragment_title_setting_iv);
        mRltitleSetting = (RelativeLayout) mRootView.findViewById(R.id.mine_fragment_title_setting_rl);
        mTitle_devide = mRootView.findViewById(R.id.mine_fragment_title_divide);
       // mSrfl = (BBswipeRefreshLayout) mRootView.findViewById(R.id.mine_fragment_swipelayout);

        //头布局
        mHeadView = View.inflate(mContext, R.layout.header_mine, null);
        mIvhead_bg = (ImageView) mHeadView.findViewById(R.id.mine_header_iv);
        mRiv_head = (RoundImageView) mHeadView.findViewById(R.id.mine_header_icon);
        mTvname = (TextView) mHeadView.findViewById(R.id.mine_header_tvname);
//        mIvvip = (ImageView) mHeadView.findViewById(R.id.mine_header_vip_icon);
        //第二个头布局
        mHeadView2 = View.inflate(mContext, R.layout.header_mine_head2, null);
        mHead2ll1 = (RelativeLayout) mHeadView2.findViewById(R.id.header_mine_head2_ll1);
        mHead2ll2 = (RelativeLayout) mHeadView2.findViewById(R.id.header_mine_head2_ll2);
        mHead2ll3 = (RelativeLayout) mHeadView2.findViewById(R.id.header_mine_head2_ll3);
        mHead2ll4 = (RelativeLayout) mHeadView2.findViewById(R.id.header_mine_head2_ll4);
        mHead2ll5 = (RelativeLayout) mHeadView2.findViewById(R.id.header_mine_head2_ll5);

        initSobot();
        initImageBg();
        initRcv();
        initEvent();
        EventBus.getDefault().register(this);
    }

    //初始化智齿客服
    public void initSobot(){
        info = new Information();
        //设置智齿客服的appkey
        info.setAppkey(key);
    }
    /**
     * 根据手机屏幕尺寸动态配置图片高度
     */
    private void initImageBg() {
        int width = AppUtil.getScreenWidth();
        mImage_bg_height = (int) ((float) (width * 160) / 375);
        ViewGroup.LayoutParams layoutParams = mIvhead_bg.getLayoutParams();
        layoutParams.height = mImage_bg_height;
        mIvhead_bg.setLayoutParams(layoutParams);
    }

    private void initRcv() {
        // mRcvAdapter = new MineRcvAdapter(null);
        mRcvAdapter = new MineCourseAdapter();
        mRcvAdapter.addHeaderView(mHeadView, 0);
        mRcvAdapter.addHeaderView(mHeadView2, 1);
        mRcv.setLayoutManager(new LinearLayoutManager(mContext));
        mRcv.setAdapter(mRcvAdapter);
        mRcv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override

            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                mOverallYScrol = mOverallYScrol + dy;
                setTitleBgColor(mOverallYScrol);
            }
        });
    }

    /**
     * 设置标题栏的颜色
     */
    private void setTitleBgColor(int space) {
        int titieHeight = AppUtil.dip2px(44);
        int restHeight = mImage_bg_height - titieHeight;
        float scale = (float) space / restHeight;
        int alpha = (int) (scale * 255);
        if (scale <= 0.2) {
            mTitle_devide.setVisibility(View.GONE);
            mRltitle_bg.setBackgroundColor(Color.parseColor("#00000000"));
            mIvtitle_setting.setBackgroundResource(R.drawable.ic_my_setting);
        } else if (scale > 0.2 && scale < 1) {
            //mTitle_devide.setVisibility(View.GONE);
            //mRltitle_bg.setBackgroundColor(Color.argb(alpha, 243, 243, 243));
            //mRltitle_bg.setBackgroundResource(R.drawable.bg_act_my_user);
            mIvtitle_setting.setBackgroundResource(R.drawable.ic_my_setting);
        } else {
            //mTitle_devide.setVisibility(View.VISIBLE);
            // mRltitle_bg.setBackgroundColor(Color.argb(255, 243, 243, 243));
            //mRltitle_bg.setBackgroundResource(R.drawable.bg_act_my_user);
            mIvtitle_setting.setBackgroundResource(R.drawable.ic_my_setting);
        }
    }

    private void initEvent() {
        mRltitleSetting.setOnClickListener(this);
        mRiv_head.setOnClickListener(this);
       // mSrfl.setOnRefreshListener(this);
        mHead2ll1.setOnClickListener(this);
        mHead2ll2.setOnClickListener(this);
        mHead2ll3.setOnClickListener(this);
        mHead2ll4.setOnClickListener(this);
        mHead2ll5.setOnClickListener(this);
        mRcvAdapter.setOnItemClickListener(this);
    }

    @Override
    public void showToast(String msg) {
        DZZWTools.showToast(mContext, msg, 0);
    }

    @Override
    public void showLoadingDialog() {

    }

    @Override
    public void dismissLoadingDialog() {

    }

    @Override
    public void refreshCustomerModule(EntityBean[] beans, List<MineMultipleitem> list) {
        //mRcvAdapter.setData(beans, list);
    }

    @Override
    public void refreshHeadIcon(String url) {
        Glide.with(AppUtil.getContext()).load(url).error(R.drawable.default_pic).into(mRiv_head);
    }

    //刷新我的课程
    @Override
    public void refreshMycourse(EntityBean[] beans) {
        mRcvAdapter.refreshData(beans);
    }


    @Override
    public void refreshName(String name) {
        mTvname.setText(name);
    }

    @Override
    public void refreshComplete() {
    //    mSrfl.setRefreshing(false);
        mRcv.smoothScrollToPosition(0);
    }

    @Override
    public void setRefreshing(boolean isRefreshing) {
    //    mSrfl.setRefreshing(isRefreshing);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.mine_fragment_title_setting_rl:
                Intent intent = new Intent(mContext, SettingActivity.class);
                mContext.startActivity(intent);
                break;
            case R.id.mine_header_icon:
                Intent intent1 = new Intent(mContext, PersonalInfoActivity.class);
                mContext.startActivity(intent1);
                break;
            case R.id.header_mine_head2_ll2: //发票管理
                Intent intent2 = new Intent(mContext, InvoiceManagerActivity.class);
                mContext.startActivity(intent2);
                break;

            case R.id.header_mine_head2_ll1: //消费记录

                //我的订单
                Intent intent3 = new Intent(mContext, MineOrderManagerActivity.class);
                mContext.startActivity(intent3);

                break;
            case R.id.header_mine_head2_ll3: //在线客服
                startSobotChat();
                break;

            case R.id.header_mine_head2_ll4: //点击我的课程 跳转到我的课程页面
                Intent intent4 = new Intent(mContext, MyCourseActivity.class);
                mContext.startActivity(intent4);
                break;

            case R.id.header_mine_head2_ll5: //点击我的HRA预约,跳转到我的HRA预约
                HraMainActivity.pushActivity((Activity) mContext,1);
                break;
        }
    }

    @Override
    public void onRefresh() {
        mPresenter.refreshAll();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void toJudgeRefresh(MineRefreshEvent mineRefreshEvent) {
        boolean bBye = mineRefreshEvent.isBBye();
        boolean customerModule = mineRefreshEvent.isCustomerModule();
        boolean headIcon = mineRefreshEvent.isHeadIcon();
        boolean name = mineRefreshEvent.isName();
        boolean vipIcon = mineRefreshEvent.isVipIcon();
//        if (bBye) {//保宝余额
//            mPresenter.refreshBbye();
//        }
        if (customerModule) { //下面动态配置的模块
            mPresenter.refreshCustomerModule();
        }
        if (headIcon) { //头像
            mPresenter.refreshHeadIcon();
        }
        if (name) { //姓名
            mPresenter.refreshName();
        }
//        if (vipIcon) { //vip的图片
//            mPresenter.refreshVipIcon();
//        }
    }


    /**
     * 课程学习完了需要更新状态
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void registerEventBus(CourseDetailEvent event) {
        if (event == null) {
            return;
        }
        if (event.isUpdateCoursePraxis() || event.isRefreshDetail() || event.isCourseBuyStatus() || event.getCoursePosition() != null) {
            mPresenter.refreshAll();
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    @Override
    public void onClick(EntityBean bean) {
        try {
            String groupid = bean.getString("groupid");
            Intent courseDetailIntent = new Intent(mContext, CourseDetailActivity2.class);
            courseDetailIntent.putExtra(CourseDetailActivity2.INTENT_EXTRA_PARAMS, groupid);  //courseid  groupid
            startActivity(courseDetailIntent);
        } catch (Exception e) {

        }
    }

    //开启智齿客服之前的初始化配置
    private void startSobotChat() {
        String userNickName = UserInfor.getInstance().getUserNickName();
        String personname = UserInfor.getInstance().getPersonname();
        String userphone = UserInfor.getInstance().getUserphone();
        //用户昵称，选填
        info.setUname(userNickName);
        //用户姓名，选填
        info.setRealname(personname);
        //用户电话，选填
        info.setTel(userphone);

        //设置标题栏的背景图片，选填
//           info.setTitleImgId(R.drawable.sobot_delete_hismsg_normal);
        //设置标题栏的背景颜色，如果背景颜色和背景图片都设置，则以背景图片为准，选填
//        info.setColor("#F2F2F2");

        SobotApi.setChatTitleDisplayMode(getContext(), SobotChatTitleDisplayMode.Default,"");
        //客服模式控制 -1不控制 按照服务器后台设置的模式运行
        //1仅机器人 2仅人工 3机器人优先 4人工优先
        Log.e("mainActivity",info.getInitModeType()+"");
        info.setArtificialIntelligenceNum(0);
        info.setInitModeType(3);
        //默认false：显示转人工按钮。true：智能转人工
        info.setArtificialIntelligence(false);

        //设置是否开启消息提醒
        SobotApi.setNotificationFlag(getContext(), sobot_isOpenNotification
                , R.drawable.sobot_demo_logo_small_icon, R.drawable.sobot_demo_logo);

        //是否使用语音功能 true使用 false不使用   默认为true
        info.setUseVoice(true);

        //返回时是否弹出满意度评价
        info.setShowSatisfaction(true);

        SobotApi.startSobotChat(getContext(), info);
    }
}
